<template>
  <div class="p-6 max-w-7xl mx-auto">
    <h1 class="text-3xl font-bold mb-6 text-red-600">RAG 深度调试与数据管理平台</h1>
    <p class="mb-6 text-gray-500">
      本页面提供对 RAG 核心流程和 ChromaDB 索引的精细控制与查看，仅供开发和调试使用。
    </p>

    <el-alert
      v-if="globalMessage"
      :title="globalMessage.title"
      :type="globalMessage.type"
      show-icon
      closable
      class="mb-6"
      @close="globalMessage = null"
    />

    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
      
      <el-card header="Collection 状态概览">
        <el-input v-model="statusConfig.collectionName" placeholder="Collection 名称" class="mb-3" />
        <el-button type="info" @click="handleCountChunks" :loading="statusLoading.count">
          查询文档块总数 ({{ statusResult.count }})
        </el-button>
        <el-tag v-if="statusResult.count !== null" :type="statusResult.count > 0 ? 'success' : 'warning'" class="ml-3">
          {{ statusResult.status }}
        </el-tag>
      </el-card>
      <el-card header="危险操作：Collection 管理">
        <el-popconfirm
          title="警告：这将永久删除整个 Collection！确认操作？"
          confirm-button-text="确认删除"
          cancel-button-text="取消"
          @confirm="handleDeleteCollection"
        >
          <template #reference>
            <el-button type="danger" plain :loading="statusLoading.deleteCol">
              删除整个 Collection ({{ statusConfig.collectionName }})
            </el-button>
          </template>
        </el-popconfirm>
      </el-card>
    </div>

    <el-card header="文档上传与索引高级操作" class="mb-8">
      <el-tabs type="border-card">
        
        <el-tab-pane label="批量文件上传 (Multi-Upload)">
          <el-upload
            ref="multiUploadRef"
            :auto-upload="false"
            :on-change="handleMultiFileChange"
            :file-list="multiFileList"
            :multiple="true"
            drag
            class="mb-4"
          >
            <el-icon class="el-icon--upload"><i-ep-upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽多个文件到此处 或 <em>点击选择</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">支持批量上传并调度后台索引任务。</div>
            </template>
          </el-upload>
          <el-button 
            type="success" 
            @click="handleMultiUpload" 
            :disabled="multiFileList.length === 0" 
            :loading="multiUploadLoading"
          >
            {{ multiUploadLoading ? '调度中...' : `上传并调度索引 (${multiFileList.length} 文件)` }}
          </el-button>
          
          <el-divider v-if="multiUploadResults.length" content-position="left">上传结果</el-divider>
          <div v-if="multiUploadResults.length" class="max-h-60 overflow-y-auto">
            <div v-for="res in multiUploadResults" :key="res.file_hash" class="mb-2">
                <el-tag 
                    :type="res.status === 'scheduled' ? 'info' : (res.status === 'duplicate' ? 'warning' : 'danger')"
                >
                    {{ res.status.toUpperCase() }}
                </el-tag>
                <span class="ml-2 text-sm">{{ res.file_name }}: {{ res.message }} (Task ID: {{ res.task_id || 'N/A' }})</span>
            </div>
        </div>
        </el-tab-pane>
        
        <el-tab-pane label="文本内容索引 (Upload From Text)">
          <el-form label-width="120px">
            <el-form-item label="Collection">
                <el-input v-model="textUploadConfig.collectionName" />
            </el-form-item>
            <el-form-item label="Material ID">
                <el-input-number v-model="textUploadConfig.materialId" controls-position="right" />
            </el-form-item>
            <el-form-item label="Paper Cut ID">
                <el-input-number v-model="textUploadConfig.paperCutId" controls-position="right" />
            </el-form-item>
            <el-form-item label="文本内容">
                <el-input v-model="textUploadConfig.textContent" type="textarea" :rows="5" placeholder="输入要索引的文本内容..." />
            </el-form-item>
            <el-form-item>
                <el-button type="warning" @click="handleUploadFromText" :loading="textUploadLoading">
                    {{ textUploadLoading ? '调度中...' : '提交文本内容索引' }}
                </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

      </el-tabs>
    </el-card>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
      
      <el-card header="文档元数据更新 (Update Metadata)">
        <el-form label-width="120px">
            <el-form-item label="Material ID">
                <el-input-number v-model="updateMetadataConfig.materialId" controls-position="right" />
            </el-form-item>
            <el-form-item label="Collection">
                <el-input v-model="updateMetadataConfig.collectionName" />
            </el-form-item>
            <el-form-item label="新标题 (示例)">
                <el-input v-model="updateMetadataConfig.title" placeholder="输入新的文档标题" />
            </el-form-item>
            <el-form-item label="是否公开">
                 <el-switch v-model="updateMetadataConfig.isPublic" active-text="公开" inactive-text="私有" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleUpdateMetadata" :loading="updateLoading">
                    {{ updateLoading ? '调度中...' : '调度元数据更新' }}
                </el-button>
            </el-form-item>
        </el-form>
      </el-card>

      <el-card header="按元数据删除文档">
        <p class="text-sm text-gray-500 mb-4">根据 Material ID 同步删除所有相关文档块。</p>
        <el-form label-width="120px">
             <el-form-item label="Collection">
                <el-input v-model="deleteByMetadataConfig.collectionName" />
            </el-form-item>
            <el-form-item label="Material ID">
                <el-input-number v-model="deleteByMetadataConfig.materialId" controls-position="right" />
            </el-form-item>
            <el-form-item>
                <el-button type="danger" @click="handleDeleteByMetadata" :loading="deleteLoading">
                    {{ deleteLoading ? '删除中...' : '同步删除文档块' }}
                </el-button>
            </el-form-item>
        </el-form>
      </el-card>
    </div>

    <el-card header="已索引文档信息查看 (Document Info Viewer)" class="mb-8">
      <el-form :inline="true" label-width="120px" class="mb-4">
        <el-form-item label="文件名关键词">
          <el-input v-model="docViewerConfig.keyword" placeholder="文件名模糊过滤" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleListDocuments" :loading="docViewerLoading.list">
            查询已上传文档列表
          </el-button>
        </el-form-item>
      </el-form>

      <el-table :data="docViewerResult.documents" style="width: 100%" height="250" border stripe v-loading="docViewerLoading.list">
        <el-table-column prop="file_name" label="文件名" min-width="350" show-overflow-tooltip />
        <el-table-column prop="file_hash" label="File Hash" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="viewDocumentMetadata(scope.row.file_hash, scope.row.file_name)">查看原始元数据</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card header="ChromaDB 索引数据窥视与删除 (Indexed Node Viewer)" class="mb-8">
      
      <el-form :inline="true" label-width="100px" class="mb-4">
        <el-form-item label="Collection">
          <el-input v-model="viewerConfig.collectionName" placeholder="默认 Collection 名称" />
        </el-form-item>
        <el-form-item label="限制数量">
          <el-input-number v-model="viewerConfig.limit" :min="1" :max="1000" controls-position="right" />
        </el-form-item>
        <el-form-item label="文件名关键词">
          <el-input v-model="viewerConfig.fileName" placeholder="file_name 模糊匹配" clearable />
        </el-form-item>
        <el-form-item label="精确 Chroma ID">
          <el-input v-model="viewerConfig.chromaId" placeholder="精确查找某个 ID" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleListIndexedNodes" :loading="viewerLoading.list">
            查询索引块
          </el-button>
        </el-form-item>
      </el-form>

      <el-divider content-position="left">索引块删除 (基于 Metadata 过滤)</el-divider>
      <el-form :inline="true" label-width="120px" class="mb-4">
        <el-form-item label="Material ID">
          <el-input-number v-model="deleteConfig.materialId" :min="1" controls-position="right" placeholder="精确 ID" clearable />
        </el-form-item>
        <el-form-item label="Title 关键字">
          <el-input v-model="deleteConfig.keyword" placeholder="文档标题模糊匹配" clearable />
        </el-form-item>
        <el-form-item label="文档类型">
          <el-input v-model="deleteConfig.docType" placeholder="例如: PaperCut" clearable />
        </el-form-item>
        <el-form-item>
          <el-popconfirm
            title="确认根据过滤器删除文档块？此操作不可逆！"
            confirm-button-text="确认删除"
            cancel-button-text="取消"
            @confirm="handleDeleteChunksByFilter"
          >
            <template #reference>
              <el-button type="danger" plain :loading="viewerLoading.delete">
                按过滤器删除文档块
              </el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>

      <el-table :data="viewerResult.nodes" style="width: 100%" height="400" border stripe v-loading="viewerLoading.list">
        <el-table-column prop="chroma_id" label="Chroma ID" width="280" show-overflow-tooltip />
        <el-table-column prop="file_name" label="文件名" width="200" show-overflow-tooltip />
        <el-table-column prop="page_label" label="页码" width="80" />
        <el-table-column prop="node_id" label="Node ID" width="180" show-overflow-tooltip />
        <el-table-column label="文本片段" min-width="250">
          <template #default="scope">
            <span class="text-xs text-gray-700">{{ scope.row.text.substring(0, 100) }}...</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="viewNodeDetail(scope.row.chroma_id)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card header="AI 元数据提取测试 (LLM Extraction)" class="mb-8">
      <el-form label-width="120px" class="mb-4">
        
        <el-form-item label="提取源类型">
          <el-radio-group v-model="extractionConfig.sourceType">
            <el-radio-button label="text">直接文本提取</el-radio-button>
            <el-radio-button label="file_key">文件键提取 (OSS/Minio)</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否公开">
          <el-switch 
            v-model="extractionConfig.isPublic" 
            active-text="公开 (true)" 
            inactive-text="非公开 (false)"
          />
        </el-form-item>

        <el-form-item v-if="extractionConfig.sourceType === 'file_key'" label="文件键 (Key)">
          <el-input v-model="extractionConfig.fileKey" placeholder="输入文件存储 Key" />
        </el-form-item>

        <el-form-item v-else label="待提取文本">
          <el-input 
            v-model="extractionConfig.textContent" 
            type="textarea" 
            :rows="4" 
            placeholder="粘贴用于提取元数据的文本..." 
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleExtractMetadata" :loading="extractionLoading">
            {{ extractionLoading ? 'AI 提取中...' : '提交 AI 元数据提取' }}
          </el-button>
        </el-form-item>
      </el-form>

      <el-divider content-position="left">提取结果</el-divider>
      <div v-if="extractionResult" class="bg-gray-50 p-4 rounded border">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="标题 (Title)">{{ extractionResult.title || 'N/A' }}</el-descriptions-item>
          <el-descriptions-item label="类型 (Doc Type)">{{ extractionResult.document_type || 'N/A' }}</el-descriptions-item>
          <el-descriptions-item label="公开 (Public)">
            <el-tag :type="extractionResult.is_public ? 'success' : 'danger'">
              {{ extractionResult.is_public }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Material ID">{{ extractionResult.material_id || 'N/A' }}</el-descriptions-item>
        </el-descriptions>
        
        <h4 class="font-semibold mt-4 mb-1">关键词 (Keywords):</h4>
        <div class="mb-3">
          <el-tag v-for="kw in extractionResult.keywords" :key="kw" class="mr-2 mb-1">{{ kw }}</el-tag>
        </div>

        <h4 class="font-semibold mb-1">摘要 (Summary):</h4>
        <p class="whitespace-pre-wrap text-sm text-gray-700">{{ extractionResult.summary || 'N/A' }}</p>
      </div>
      <el-empty v-else description="执行提取以查看结果" :image-size="80" />
    </el-card>
    
    <el-card header="通用 MCP 调度接口测试 (Multi-Component Planner)" class="mb-8">
      <el-form label-width="120px" class="mb-4">
        
        <el-form-item label="会话 ID">
          <el-input v-model="mcpConfig.sessionId" placeholder="会话 ID (可选)" />
        </el-form-item>

        <el-form-item label="自然语言问题">
          <el-input 
            v-model="mcpConfig.question" 
            type="textarea" 
            :rows="3" 
            placeholder="输入用于规划器调度的复杂问题..." 
          />
        </el-form-item>

        <el-form-item>
          <el-button type="danger" @click="handleDispatchMcpCommand" :loading="mcpLoading">
            {{ mcpLoading ? '规划调度中...' : '提交 MCP 调度指令' }}
          </el-button>
        </el-form-item>
      </el-form>

      <el-divider content-position="left">指令输出</el-divider>
      <div v-if="mcpResult" class="bg-gray-50 p-4 rounded border">
        <h4 class="font-semibold mb-1">规划动作 (Action): <el-tag type="success">{{ mcpResult.action }}</el-tag></h4>
        
        <h4 class="font-semibold mt-3 mb-1">推理过程 (Reasoning):</h4>
        <p class="whitespace-pre-wrap text-sm text-gray-700 mb-3">{{ mcpResult.reasoning || 'N/A' }}</p>

        <h4 class="font-semibold mb-1">指令参数 (Arguments):</h4>
        <pre class="bg-white p-2 rounded text-xs whitespace-pre-wrap max-h-60 overflow-auto border">{{ JSON.stringify(mcpResult.arguments, null, 2) }}</pre>
      </div>
      <el-empty v-else description="执行调度以查看指令输出" :image-size="80" />
    </el-card>
    
    <el-card header="完整的 RAG 流程调试 (Debug RAG Flow)">
      <el-form label-width="120px" class="mb-4">
        <el-form-item label="Collection 名称">
          <el-input v-model="ragDebugConfig.collectionName" placeholder="输入 Collection 名称" />
        </el-form-item>
        <el-form-item label="查询问题">
          <el-input v-model="ragDebugConfig.question" type="textarea" :rows="2" placeholder="输入测试问题..." />
        </el-form-item>
        <el-form-item label="目标文件 ID">
          <el-input v-model="ragDebugConfig.targetFileIdsStr" placeholder="多个 ID 以逗号分隔，例如 1,2,3" />
        </el-form-item>
        <el-form-item label="初始召回 K (可选)">
          <el-input-number v-model="ragDebugConfig.similarityTopK" :min="1" controls-position="right" placeholder="默认使用配置的 K" />
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="handleDebugRagFlow" :loading="ragDebugLoading">
            {{ ragDebugLoading ? '调试中...' : '执行完整 RAG 流程调试' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <el-divider content-position="left">调试结果</el-divider>
      <div v-if="ragDebugResult.final_response_content">
        <el-tabs>
          <el-tab-pane label="最终回答" name="answer">
            <pre class="bg-gray-100 p-4 rounded text-sm whitespace-pre-wrap">{{ ragDebugResult.final_response_content }}</pre>
            <h4 class="font-semibold mt-4">引用信息 (Citations)</h4>
            <el-table :data="ragDebugResult.citations" border size="small" max-height="250">
              <el-table-column prop="sentence" label="回答句子" width="300" show-overflow-tooltip />
              <el-table-column prop="file_name" label="引用文件" width="180" show-overflow-tooltip />
              <el-table-column prop="page_label" label="页码" width="80" />
              <el-table-column prop="referenced_chunk_id" label="Chunk ID" min-width="250" show-overflow-tooltip />
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="召回节点 (重排后)" name="final_nodes">
            <el-table :data="ragDebugResult.final_retrieved_nodes" border size="small" max-height="300">
              <el-table-column prop="score" label="Score" width="80" />
              <el-table-column prop="text_snippet" label="文本片段" show-overflow-tooltip />
              <el-table-column prop="metadata.file_name" label="文件名" width="180" show-overflow-tooltip />
              <el-table-column prop="metadata.page_label" label="页码" width="80" />
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="初始召回节点" name="original_nodes">
            <el-table :data="ragDebugResult.original_retrieved_nodes" border size="small" max-height="300">
              <el-table-column prop="score" label="Score" width="80" />
              <el-table-column prop="text_snippet" label="文本片段" show-overflow-tooltip />
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="最终 LLM Prompt" name="prompt">
            <pre class="bg-gray-100 p-4 rounded text-sm whitespace-pre-wrap max-h-96 overflow-auto">{{ ragDebugResult.final_llm_prompt }}</pre>
          </el-tab-pane>
        </el-tabs>
      </div>
      <el-empty v-else description="执行 RAG 流程以查看详细结果" :image-size="100" />
    </el-card>

    <el-drawer v-model="drawerVisible" :title="`节点详情: ${nodeDetail.chroma_id}`" direction="rtl" size="50%">
      <div v-loading="drawerLoading">
        <h3 class="font-semibold mb-2">节点文本</h3>
        <pre class="bg-gray-50 p-3 border rounded text-xs whitespace-pre-wrap mb-4">{{ nodeDetail.text }}</pre>

        <h3 class="font-semibold mb-2">元数据 (Metadata)</h3>
        <pre class="bg-gray-50 p-3 border rounded text-xs whitespace-pre-wrap">{{ JSON.stringify(nodeDetail.metadata, null, 2) }}</pre>

        <div v-if="nodeDetail.docChunks.length > 0">
          <h3 class="font-semibold mb-2">文档原始分块 ({{ nodeDetail.docChunks.length }} 个)</h3>
          <el-collapse>
            <el-collapse-item v-for="(chunk, index) in nodeDetail.docChunks" :key="index" :title="`分块 ${index + 1} (页码: ${chunk.metadata.page_label})`">
              <h4 class="font-medium text-gray-700 mb-1">分块文本片段:</h4>
              <pre class="bg-gray-100 p-3 rounded text-xs whitespace-pre-wrap max-h-40 overflow-auto">{{ chunk.text }}</pre>
              <h4 class="font-medium text-gray-700 mt-2">元数据:</h4>
              <el-tag size="small" type="info">文件名: {{ chunk.metadata.file_name }}</el-tag>
            </el-collapse-item>
          </el-collapse>
        </div>

        <div v-else>
          <h3 class="font-semibold mb-2">节点文本</h3>
          <pre class="bg-gray-50 p-3 border rounded text-xs whitespace-pre-wrap mb-4">{{ nodeDetail.text }}</pre>

          <h3 class="font-semibold mb-2">元数据 (Metadata)</h3>
          <pre class="bg-gray-50 p-3 border rounded text-xs whitespace-pre-wrap">{{ JSON.stringify(nodeDetail.metadata, null, 2) }}</pre>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { 
  listIndexedNodes, 
  deleteEntireCollection, 
  countChunks,
  debugRagFlow,
  deleteChunksByFilter,
  getNodeById
} from '~/api/debugApi';

import {
  listDocuments,
  getDocumentMetadata,
  type DocumentInfo,
  type DocumentChunk
} from '~/api/documentsApi';

import {
  extractDocumentMetadata,
  type ExtractedDocumentMetadata,
  type ExtractionRequestPayload
} from '~/api/extractionApi';

import {
  dispatchMcpCommand,
  type MCPCommand
} from '~/api/mcpApi';

import {
    uploadMultipleFiles,
    deleteByMetadata,
    updateDocumentMetadata,
    uploadFromText,
    getTaskStatus,
    type TaskStatus,
    type UploadFromTextRequestPayload,
    type UpdateMetadataRequestPayload,
    type DeleteByMetadataRequestPayload
} from '~/api/uploadApi';

import { type IndexedNode } from '~/api/debugApi'; // 导入类型
import type { ElUpload } from 'element-plus';

interface GlobalAlertMessage {
  title: string;
  type: 'success' | 'error' | 'warning' | 'info';
}

const globalMessage = ref<GlobalAlertMessage | null>(null); 
const setGlobalMessage = (title:string, type: GlobalAlertMessage['type'] = 'success') => {
  globalMessage.value = { title, type };
  setTimeout(() => { globalMessage.value = null; }, 5000);
};

// --- Collection 状态/维护 ---
const statusConfig = reactive({
  collectionName: 'public_collection',
});
const statusLoading = reactive({
  count: false,
  splitting: false,
  deleteCol: false,
});
const statusResult = reactive({
  count: null as (number | null),
  status: '',
});

// --- 文档信息查询状态 ---
const docViewerConfig = reactive({
  keyword: '', // 文件名过滤关键词
});
const docViewerLoading = reactive({
  list: false,
  detail: false,
});
const docViewerResult = reactive({
  documents: [] as DocumentInfo[],
});

// --- AI 提取状态 ---
const extractionConfig = reactive({
  sourceType: 'text', // 'text' 或 'file_key'
  fileKey: '',
  textContent: '本文件是关于检察院办理未成年人犯罪案件的指导意见。其中详细规定了取保候审的条件和程序。',
  isPublic: true,
});
const extractionLoading = ref(false);
const extractionResult = ref<ExtractedDocumentMetadata | null>(null);

// --- MCP 调度状态 ---
const mcpConfig = reactive({
  question: '请帮我查询所有关于检察院办理未成年人案件的文件，并给我一个摘要。',
  sessionId: 'test_mcp_session',
});
const mcpLoading = ref(false);
const mcpResult = ref<MCPCommand | null>(null);

// 处理 文档块总数 查询
const handleCountChunks = async () => {
  if (!statusConfig.collectionName) {
    setGlobalMessage('请输入 Collection 名称', 'warning');
    return;
  }
  statusLoading.count = true;
  try {
    const result = await countChunks(statusConfig.collectionName);
    statusResult.count = result.count;
    statusResult.status = result.status === 'success' ? '存在' : '未找到';
    setGlobalMessage(`Collection [${statusConfig.collectionName}] 块数: ${result.count}`, 'success');
  } catch (error) {
    statusResult.count = null;
    statusResult.status = '查询失败';

    let errorMessage = '未知错误';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    setGlobalMessage(`查询失败: ${errorMessage}`, 'error');
  } finally {
    statusLoading.count = false;
  }
};

// 处理 删除 Collection
const handleDeleteCollection = async () => {
  if (!statusConfig.collectionName) {
    setGlobalMessage('请输入 Collection 名称', 'warning');
    return;
  }
  statusLoading.deleteCol = true;
  try {
    const result = await deleteEntireCollection(statusConfig.collectionName);
    setGlobalMessage(result.message, 'warning');
    statusResult.count = 0; // 假定删除成功，更新计数
  } catch (error) {
    let errorMessage = '未知错误';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    setGlobalMessage(`删除失败: ${errorMessage}`, 'error');
  } finally {
    statusLoading.deleteCol = false;
  }
};

// --- 索引块查看器 (Node Viewer) ---
const viewerConfig = reactive({
  collectionName: 'public_collection',
  limit: 20,
  fileName: '',
  chromaId: '',
  title: '',
});
const viewerLoading = reactive({
  list: false,
  delete: false,
});
const viewerResult = reactive({
  nodes: [] as IndexedNode[],
});
const deleteConfig = reactive({
  materialId: null,
  keyword: '',
  docType: '',
});


// --- 批量上传状态 ---
const multiUploadRef = ref<InstanceType<typeof ElUpload> | null>(null); 
const multiFileList = ref<File[]>([]);
const multiUploadLoading = ref(false);
const multiUploadResults = ref<any[]>([]);

// --- 文本索引状态 ---
const textUploadConfig = reactive({
    textContent: '测试文本内容。',
    materialId: 1000,
    paperCutId: 5000,
    collectionName: 'public_collection',
});
const textUploadLoading = ref(false);

// --- 元数据更新状态 ---
const updateMetadataConfig = reactive({
    materialId: 1000,
    collectionName: 'public_collection',
    title: '更新后的标题',
    isPublic: true,
});
const updateLoading = ref(false);

// --- 批量删除状态 ---
const deleteByMetadataConfig = reactive({
    collectionName: 'public_collection',
    materialId: 1000,
});
const deleteLoading = ref(false);


// 处理 索引块列表 查询
const handleListIndexedNodes = async () => {
  if (!viewerConfig.collectionName) {
    setGlobalMessage('请输入 Collection 名称', 'warning');
    return;
  }
  viewerLoading.list = true;
  viewerResult.nodes = [];
  try {
    const nodes = await listIndexedNodes(
      viewerConfig.collectionName,
      viewerConfig.limit,
      viewerConfig.fileName,
      viewerConfig.chromaId,
      viewerConfig.title
    );
    viewerResult.nodes = nodes;
    setGlobalMessage(`成功查询到 ${nodes.length} 个索引块。`, 'info');
  } catch (error) {
    let errorMessage = '未知错误';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    setGlobalMessage(`查询索引块失败: ${errorMessage}`, 'error');
  } finally {
    viewerLoading.list = false;
  }
};

// 处理 过滤删除 文档块
const handleDeleteChunksByFilter = async () => {
  if (!viewerConfig.collectionName) {
    setGlobalMessage('请输入 Collection 名称', 'warning');
    return;
  }
  if (!deleteConfig.materialId && !deleteConfig.keyword && !deleteConfig.docType) {
    setGlobalMessage('请至少填写 Material ID, Title 关键字 或 文档类型之一进行过滤删除。', 'warning');
    return;
  }
  
  viewerLoading.delete = true;
  try {
    const result = await deleteChunksByFilter(
      viewerConfig.collectionName,
      deleteConfig.materialId!,
      deleteConfig.keyword,
      deleteConfig.docType
    );
    setGlobalMessage(result.message, 'warning');
    // 自动刷新列表
    await handleListIndexedNodes();
  } catch (error) {
    let errorMessage = '未知错误';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    setGlobalMessage(`删除失败: ${errorMessage}`, 'error');
  } finally {
    viewerLoading.delete = false;
  }
};

// 节点详情抽屉
const drawerVisible = ref(false);
const drawerLoading = ref(false);
const nodeDetail = reactive({
  chroma_id: '',
  text: '',
  metadata: {},
  docChunks: [] as DocumentChunk[], 
});


// 处理 文档列表 查询
const handleListDocuments = async () => {
  docViewerLoading.list = true;
  docViewerResult.documents = [];
  try {
    const docs = await listDocuments(docViewerConfig.keyword);
    docViewerResult.documents = docs;
    setGlobalMessage(`成功查询到 ${docs.length} 个文档。`, 'info');
  } catch (error) {
    let errorMessage = '未知错误';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    setGlobalMessage(`查询文档列表失败: ${errorMessage}`, 'error');
  } finally {
    docViewerLoading.list = false;
  }
};

// 查看文档原始元数据 (在抽屉中展示)
const viewDocumentMetadata = async (fileHash: string, fileName: string) => {
  drawerVisible.value = true;
  drawerLoading.value = true;
  nodeDetail.chroma_id = `Doc Hash: ${fileHash}`;
  nodeDetail.text = `正在加载文档 ${fileName} 的原始分块信息...`;
  nodeDetail.metadata = {};
  nodeDetail.docChunks = []; // 清空之前的分块信息

  try {
    const chunks = await getDocumentMetadata(fileHash);
    nodeDetail.docChunks = chunks;
    nodeDetail.text = `文档共包含 ${chunks.length} 个分块 (Page/Block)。`;
    setGlobalMessage(`成功获取文档 [${fileName}] 元数据详情`, 'info');
  } catch (error) {
    let errorMessage = '未知错误';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    nodeDetail.text = `加载失败: ${errorMessage}`;
    setGlobalMessage(`获取文档详情失败: ${errorMessage}`, 'error');
  } finally {
    drawerLoading.value = false;
  }
};

const viewNodeDetail = async (chromaId:any) => {
  drawerVisible.value = true;
  drawerLoading.value = true;
  nodeDetail.chroma_id = chromaId;
  nodeDetail.text = '加载中...';
  nodeDetail.metadata = {};
  
  try {
    const detail = await getNodeById(viewerConfig.collectionName, chromaId);
    nodeDetail.text = detail.text;
    nodeDetail.metadata = detail.metadata;
    setGlobalMessage(`成功获取节点 [${chromaId}] 详情`, 'info');
  } catch (error) {
    let errorMessage = '未知错误';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    nodeDetail.text = `加载失败: ${errorMessage}`;
    setGlobalMessage(`获取详情失败: ${errorMessage}`, 'error');
  } finally {
    drawerLoading.value = false;
  }
};


// --- 完整 RAG 流程调试 ---
const ragDebugConfig = reactive({
  collectionName: 'public_collection',
  question: '检察院对于办理网络犯罪案件的最新指导意见是什么？',
  targetFileIdsStr: '', // 逗号分隔的字符串
  similarityTopK: null,
});
const ragDebugLoading = ref(false);
const ragDebugResult = reactive({
  query_text: '',
  final_llm_prompt: '',
  original_retrieved_nodes: [],
  final_retrieved_nodes: [],
  final_response_content: '',
  citations: [],
});

const handleDebugRagFlow = async () => {
  if (!ragDebugConfig.collectionName || !ragDebugConfig.question) {
    setGlobalMessage('请输入 Collection 名称和查询问题。', 'warning');
    return;
  }
  
  ragDebugLoading.value = true;
  // 构造请求体
  const payload = {
    question: ragDebugConfig.question,
    account_id: 99999,
    collection_name: ragDebugConfig.collectionName,
    target_file_ids: ragDebugConfig.targetFileIdsStr
      ? ragDebugConfig.targetFileIdsStr.split(',').map(s => s.trim()).filter(s => s)
      : [],
    similarity_top_k: ragDebugConfig.similarityTopK !== null 
      ? ragDebugConfig.similarityTopK 
      : undefined, 
    filters: {}, // 暂不提供复杂的 JSON 过滤器输入
  };
  
  try {
    const result = await debugRagFlow(payload);
    // 填充结果
    Object.assign(ragDebugResult, result);
    setGlobalMessage('完整 RAG 流程调试成功，请查看下方 Tab。', 'success');
  } catch (error) {
    let errorMessage = '未知错误';
    if (error instanceof Error) {
      errorMessage = error.message;
    }
    setGlobalMessage(`RAG 流程调试失败: ${errorMessage}`, 'error');
    // 清空结果
    Object.assign(ragDebugResult, {
      query_text: '',
      final_llm_prompt: '',
      original_retrieved_nodes: [],
      final_retrieved_nodes: [],
      final_response_content: '',
      citations: [],
    });
  } finally {
    ragDebugLoading.value = false;
  }
};

// -------------------------------------------------------------------
// --- AI 元数据提取 ---
// -------------------------------------------------------------------

const handleExtractMetadata = async () => {
    extractionLoading.value = true;
    extractionResult.value = null;
    
    // 构造 Payload
    let payload: ExtractionRequestPayload = {
        is_public: extractionConfig.isPublic,
        file_key: null,
        content: null,
    };

    if (extractionConfig.sourceType === 'file_key') {
        if (!extractionConfig.fileKey) {
            setGlobalMessage('请输入文件键 (File Key)。', 'warning');
            extractionLoading.value = false;
            return;
        }
        payload.file_key = extractionConfig.fileKey;
    } else {
        if (!extractionConfig.textContent) {
            setGlobalMessage('请输入文本内容。', 'warning');
            extractionLoading.value = false;
            return;
        }
        payload.content = extractionConfig.textContent;
    }
    
    try {
        const result = await extractDocumentMetadata(payload);
        extractionResult.value = result;
        setGlobalMessage('AI 元数据提取成功，请查看结果。', 'success');
    } catch (error) {
        let errorMessage = '未知错误';
        if (error instanceof Error) {
            errorMessage = error.message;
        }
        setGlobalMessage(`AI 元数据提取失败: ${errorMessage}`, 'error');
    } finally {
        extractionLoading.value = false;
    }
};


// -------------------------------------------------------------------
// --- MCP 调度 ---
// -------------------------------------------------------------------

const handleDispatchMcpCommand = async () => {
    if (!mcpConfig.question) {
        setGlobalMessage('请输入要调度的自然语言问题。', 'warning');
        return;
    }
    
    mcpLoading.value = true;
    mcpResult.value = null;
    
    const payload = {
        question: mcpConfig.question,
        session_id: mcpConfig.sessionId || undefined,
        account_id: 'test_user_id', // 示例用户 ID
    };
    
    try {
        const result = await dispatchMcpCommand(payload);
        mcpResult.value = result;
        setGlobalMessage('MCP 指令调度成功，请查看指令输出。', 'success');
    } catch (error) {
        let errorMessage = '未知错误';
        if (error instanceof Error) {
            errorMessage = error.message;
        }
        setGlobalMessage(`MCP 指令调度失败: ${errorMessage}`, 'error');
    } finally {
        mcpLoading.value = false;
    }
};


// 1. 批量上传处理
const handleMultiFileChange = (file: any, fileList: any) => {
    // 提取 raw File 对象
    multiFileList.value = fileList.map((f: any) => f.raw).filter((f: any) => f);
};

const handleMultiUpload = async () => {
    if (multiFileList.value.length === 0) {
        setGlobalMessage('请选择要批量上传的文件。', 'warning');
        return;
    }
    multiUploadLoading.value = true;
    multiUploadResults.value = [];

    try {
        const responses = await uploadMultipleFiles(multiFileList.value);
        multiUploadResults.value = responses;
        setGlobalMessage(`批量上传完成。已调度 ${responses.filter(r => r.status === 'scheduled').length} 个任务。`, 'success');
    } catch (error) {
        let errorMessage = '未知错误';
        if (error instanceof Error) { errorMessage = error.message; }
        setGlobalMessage(`批量上传失败: ${errorMessage}`, 'error');
    } finally {
        multiUploadLoading.value = false;
        // 清空列表
        multiFileList.value = [];
        if (multiUploadRef.value) { multiUploadRef.value.clearFiles(); }
    }
};

// 2. 文本内容索引
const handleUploadFromText = async () => {
    if (!textUploadConfig.textContent) {
        setGlobalMessage('请输入文本内容。', 'warning');
        return;
    }

    textUploadLoading.value = true;
    
    const payload: UploadFromTextRequestPayload = {
        text_content: textUploadConfig.textContent,
        collection_name: textUploadConfig.collectionName,
        metadata: {
            material_id: textUploadConfig.materialId,
            paper_cut_id: textUploadConfig.paperCutId,
            // ... 其他元数据
        }
    };

    try {
        const result = await uploadFromText(payload);
        setGlobalMessage(`文本索引任务 [${result.task_id}] 已调度。`, 'success');
    } catch (error) {
        let errorMessage = '未知错误';
        if (error instanceof Error) { errorMessage = error.message; }
        setGlobalMessage(`文本索引调度失败: ${errorMessage}`, 'error');
    } finally {
        textUploadLoading.value = false;
    }
};

// 3. 元数据更新
const handleUpdateMetadata = async () => {
    const { materialId, collectionName, title, isPublic } = updateMetadataConfig;

    const payload: UpdateMetadataRequestPayload = {
        material_id: materialId,
        collection_name: collectionName,
        metadata: {
            title: title,
            // 假设 is_public 通过 accessible_to 字段控制
            accessible_to: isPublic ? ['public'] : [], 
        }
    };

    try {
        const result = await updateDocumentMetadata(payload);
        setGlobalMessage(`元数据更新任务 [${result.task_id}] 已调度。`, 'success');
    } catch (error) {
        let errorMessage = '未知错误';
        if (error instanceof Error) { errorMessage = error.message; }
        setGlobalMessage(`元数据更新调度失败: ${errorMessage}`, 'error');
    }
};

// 4. 批量删除
const handleDeleteByMetadata = async () => {
    const { collectionName, materialId } = deleteByMetadataConfig;
    
    const payload: DeleteByMetadataRequestPayload = {
        collection_name: collectionName,
        // 根据 materialId 构建过滤器
        filters: { material_id: { "$eq": materialId } } 
    };

    deleteLoading.value = true;
    try {
        const result = await deleteByMetadata(payload);
        setGlobalMessage(`成功删除文档块: ${result.message}`, 'warning');
    } catch (error) {
        let errorMessage = '未知错误';
        if (error instanceof Error) { errorMessage = error.message; }
        setGlobalMessage(`删除失败: ${errorMessage}`, 'error');
    } finally {
        deleteLoading.value = false;
    }
};

</script>

<style scoped>
.text-sm {
  font-size: 0.875rem;
}
.text-xs {
  font-size: 0.75rem;
}
</style>